import { defineStore } from 'pinia'
import { RouteLocationRaw } from 'vue-router'

import { generateStoreNameInStorage } from '@/store/helper'

import settings, { Theme, NavMode } from '@/config/settings'

import router from '@/router'
import { StateType } from './types'
import { TabNavItem, equalTabNavRoute } from '@/utils/routes'

// const homeRoute = router.resolve(settings.homeRouteItem.path);

// store名称
const storeName = 'global'

const initState: StateType = {
  collapsed: false,
  headFixed: settings.headFixed,
  tabNavEnable: settings.tabNavEnable,
  headTabNavList: [
    // {
    //   route: homeRoute,
    //   menu: settings.homeRouteItem,
    // },
  ],
  topNavEnable: settings.topNavEnable,
  theme: settings.theme,
  navMode: settings.navMode,
  leftSiderFixed: settings.leftSiderFixed,
  isRefreshToken: false,
  requestsList: [],
}

export const useGlobalStore = defineStore(storeName, {
  state: (): StateType => ({
    ...initState,
  }),
  actions: {
    changeLayoutCollapsed(payload) {
      this.collapsed = payload
    },
    setHeadFixed(payload) {
      this.headFixed = payload
    },
    setTabNavEnable(payload) {
      this.tabNavEnable = payload
    },
    setHeadTabNavList(payload) {
      this.headTabNavList = payload
    },
    /**
     * 关闭当前tabNav，并跳转自定义路由
     * @param payload RouteLocationRaw 跳转路由参数，必须
     */
    closeCurrentHeadTabNav(payload: RouteLocationRaw) {
      const navList: TabNavItem[] = this.headTabNavList.filter(
        (item2: TabNavItem) => !equalTabNavRoute(router.currentRoute.value, item2.route, item2.menu.tabNavType)
      )
      this.headTabNavList = [...navList]

      router.push(payload)
    },
    setTopNavEnable(payload) {
      this.topNavEnable = payload
    },
    setTheme(payload) {
      this.theme = payload
    },
    setNavMode(payload) {
      this.navMode = payload
    },
    setLeftSiderFixed(payload) {
      this.leftSiderFixed = payload
    },
  },
  // persist: {
  //   key: generateStoreNameInStorage(storeName),
  // },
})
